package com.bckj.fastboot.core.jackson;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class JsonUtils implements ApplicationContextAware {
    private static ObjectMapper objectMapper;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        objectMapper = applicationContext.getBean(ObjectMapper.class);
    }

    @SneakyThrows
    public static String toJsonStr(Object value) {
        return objectMapper.writeValueAsString(value);
    }

    @SneakyThrows
    public static  <T> T toBean(String jsonString, Class<T> beanClass) {
        return objectMapper.readValue(jsonString, beanClass);
    }

    @SneakyThrows
    public static <T> T toBean(String jsonString, TypeReference<T> valueTypeRef) {
        return objectMapper.readValue(jsonString, valueTypeRef);
    }

    public static <T> T convertValue(Object fromValue, Class<T> toValueType) {
        return objectMapper.convertValue(fromValue, toValueType);
    }
}
